<?php
namespace Admin\Model;
use Think\Model;
use Think\Verify;

class OrderModel extends Model{
	private $where;
	private $recycle;
	
	//自动验证
	protected $_validate = array(
		array('tid','require','请先在模板管理模块下添加一个模板！',self::EXISTS_VALIDATE),
		array('price','currency','成交单价必须是数字！',self::EXISTS_VALIDATE),
		array('count','number','订购数量必须是数字！',self::EXISTS_VALIDATE),
		array('name','2,20','姓名不得小于2位或大于20位！',self::EXISTS_VALIDATE,'length'),
		array('tel','7,20','联系电话不得小于7位或大于20位！',self::EXISTS_VALIDATE,'length'),
		array('province','require','请选择省份！',self::EXISTS_VALIDATE),
		array('city','require','请选择城市！',self::EXISTS_VALIDATE),
		//array('county','require','请选择区/县！',self::EXISTS_VALIDATE),
		array('province2','2,5','省份不得小于2位或大于5位！',self::EXISTS_VALIDATE,'length'),
		array('city2','2,15','城市不得小于2位或大于15位！',self::EXISTS_VALIDATE,'length'),
		//array('county2','2,15','区/县不得小于2位或大于15位！',self::EXISTS_VALIDATE,'length'),
		array('address','5,200','街道地址不得小于5位或大于200位！',self::EXISTS_VALIDATE,'length'),
		array('post','/^\d{6}$/','邮政编码必须是6位的数字！',self::VALUE_VALIDATE),
		array('note','1,250','备注不得大于250位！',self::VALUE_VALIDATE,'length'),
		array('email','email','电子邮箱格式不合法！',self::VALUE_VALIDATE),
		array('logistics_id','1,30','物流编号不得大于30位！',self::VALUE_VALIDATE,'length'),
	);
	
	//初始化
	public function _initialize(){
		$session = session(C('SESSION_KEY'));
		$sqlWhere = array(1=>array('uid'=>$session['id']),2=>array('uid'=>array('IN',$session['id'].',0')),3=>'1=1');
		$this->where = $session['level']==2 ? $sqlWhere[$session['order_permit']] : $sqlWhere[3];
		$this->recycle = CONTROLLER_NAME=='Recycle';
	}
	
	//查询总记录
	public function total(){
		return $this->where($this->map($this->recycle))->count();
	}
	
	//查询未发货数
	public function total2(){
		$map = array(
			'state'=>1,
			'recycle'=>0
		);
		return $this->where($map)->count();
	}
	
	//查询已发货数
	public function total3(){
		$map = array(
			'state'=>2,
			'recycle'=>0
		);
		return $this->where($map)->count();
	}
	
	//查询已取消数
	public function total4(){
		$map = array(
			'state'=>3,
			'recycle'=>0
		);
		return $this->where($map)->count();
	}
	
	//查询所有
	public function all($firstRow){
		return $this->field('id,oid,uid,tid,pid,price,count,name,tel,province,city,county,address,post,note,email,ip,referrer,pay,state,lid,logistics_id,date')
    				->where($this->map($this->recycle))
    				->order(array('date'=>'DESC'))
    				->limit($firstRow,C('PAGE_SIZE'))
    				->select();
	}
	
	//查询所有（不分页）
	public function all2(){
		return $this->field('id,oid,uid,tid,pid,price,count,name,tel,province,city,county,address,post,note,email,ip,referrer,pay,state,lid,logistics_id,date')
    				->where($this->map($this->recycle))
    				->order(array('date'=>'DESC'))
    				->select();
	}
	
	//查询所有（不分页，IN）
	public function all3(){
		$map = array(
			'id'=>array('IN',I('post.ids')),
			'recycle'=>$this->recycle
		);
		$map[] = $this->where;
		return $this->field('id,oid,uid,tid,pid,price,count,name,tel,province,city,county,address,post,note,email,ip,referrer,pay,state,lid,logistics_id,date')
    				->where($map)
    				->order(array('date'=>'DESC'))
    				->select();
	}
	
	//前台查单
	public function all4(){
		$map['recycle'] = 0;
		if (C('ORDER_SEARCH_STEP') == '0') $map['tid'] = I('get.tid');
		if (I('get.field') == 1){
			$map['oid'] = I('get.keyword');
		}elseif (I('get.field') == 2){
			$map['name'] = I('get.keyword');
		}elseif (I('get.field') == 3){
			$map['tel'] = I('get.keyword');
		}
		return $this->field('id,oid,uid,tid,pid,price,count,name,tel,province,city,county,address,post,note,email,ip,referrer,pay,state,lid,logistics_id,date')
    				->where($map)
    				->order(array('date'=>'DESC'))
    				->select();
	}
	
	//按自定义时间统计
	public function diyTime($time1,$time2){
		$map[] = $this->map();
		$map['_string'] = "`date`>='".strtotime($time1.' 00:00:00')."' AND `date`<='".strtotime($time2.' 23:59:59')."'";
		return $this->field('COUNT(CASE WHEN state=1 THEN id END) count1,SUM(CASE WHEN state=1 THEN price*count ELSE 0 END) sum1,COUNT(CASE WHEN state=2 THEN id END) count2,SUM(CASE WHEN state=2 THEN price*count ELSE 0 END) sum2,COUNT(CASE WHEN state=3 THEN id END) count3,SUM(CASE WHEN state=3 THEN price*count ELSE 0 END) sum3')
	    			->where($map)
					->select();
	}
	
	//按天、月、年统计
	public function dayMonthYear($time,$firstRow=-1){
		switch (I('get.order')){
			case 0: $order = 'time';
			break;
			case 1: $order = 'count1';
			break;
			case 2: $order = 'count2';
			break;
			case 3: $order = 'count3';
			break;
			case 4: $order = 'sum1';
			break;
			case 5: $order = 'sum2';
			break;
			case 6: $order = 'sum3';
			break;
		}
		$object = $this->field('COUNT(CASE WHEN state=1 THEN id END) count1,SUM(CASE WHEN state=1 THEN price*count ELSE 0 END) sum1,COUNT(CASE WHEN state=2 THEN id END) count2,SUM(CASE WHEN state=2 THEN price*count ELSE 0 END) sum2,COUNT(CASE WHEN state=3 THEN id END) count3,SUM(CASE WHEN state=3 THEN price*count ELSE 0 END) sum3,FROM_UNIXTIME(date,"'.$time.'") time')
	    			   ->group('time')
	    			   ->where($this->map())
	    			   ->order(array($order=>'DESC'));
    	return $firstRow>=0 ? $object->limit($firstRow,C('PAGE_SIZE'))->select() : $object->select();
	}
	
	//查询一条
	public function one(){
		$map['id'] = I('get.id');
		$map[] = $this->where;
		$map['recycle'] = $this->recycle;
		return $this->field('oid,uid,tid,pid,price,count,name,tel,province,city,county,address,post,note,email,ip,qqau,referrer,pay,state,lid,logistics_id,date')->where($map)->find();
	}
	
	//查询支付信息
	public function one2($oid=0){
		$map['oid'] = $oid ? $oid : I('get.oid');
		return $this->field('tid,pid,price,count,pay')->where($map)->find();
	}
	
	//查询最老一条
	public function older(){
		$map['recycle'] = 0;
		$map[] = $this->where;
		return $this->field('date')->where($map)->order(array('date'=>'ASC'))->find();
	}
	
	//查询最新一条
	public function newer(){
		$map['recycle'] = 0;
		$map[] = $this->where;
		return $this->field('date')->where($map)->order(array('date'=>'DESC'))->find();
	}
	
	
	//添加
	public function insert($type=0){
		$Template = D('Admin/Template');
		$object = $Template->one(I('post.tid'));
		if ($type && !$object) return '此下单模板已被删除！';
		$data = array(
			'oid'=>NOW_TIME,
			'tid'=>I('post.tid'),
			'pid'=>I('post.pid'),
			'pay'=>I('post.pay'),
			'ip'=>$_SERVER['REMOTE_ADDR'],
			'date'=>NOW_TIME
		);
		$fieldTemp = explode(',',$object['field']);
		if (in_array(2,$fieldTemp)) $data['name'] = I('post.name');
		if (in_array(3,$fieldTemp)) $data['tel'] = I('post.tel');
		if (in_array(6,$fieldTemp)) $data['address'] = I('post.address');
		if (in_array(7,$fieldTemp)) $data['post'] = I('post.post');
		if (in_array(8,$fieldTemp)) $data['note'] = I('post.note');
		if (in_array(9,$fieldTemp)) $data['email'] = I('post.email');
		if ($type == 0){
			$session = session(C('SESSION_KEY'));
			$data['uid'] = $session['id'];
			$data['price'] = I('post.price');
			$data['count'] = I('post.count');
			$data['state'] = I('post.state');
			$data['lid'] = I('post.lid');
			$data['logistics_id'] = I('post.logistics_id');
		}else{
			$data['uid'] = $object['uid'];
			$Product = D('Admin/Product');
			$object2 = $Product->one(I('post.pid'));
			$data['price'] = $object2 ? $object2['price'] : '0.00';
			$data['count'] = in_array(1,$fieldTemp) ? I('post.count') : 1;
			$data['state'] = $object['state'];
			$data['referrer'] = I('post.referrer');
			if ($object['qq']){
				$session = session('QC_userData');
				if (strlen($session['openid']) == 32){
					$data['qqau'] = $session['openid'];
				}else{
					return '请登录QQ后下单！';
				} 
			}
			$data['success'] = str_replace('{oid}',$data['oid'],$object['success']);
		}
		if (in_array(4,$fieldTemp) && in_array(5,$fieldTemp)){
			if (I('post.type') == 'a'){
				$data['province'] = I('post.province');
				$data['city'] = I('post.city');
				$data['county'] = I('post.county');
			}elseif (I('post.type') == 'b'){
				$data['province2'] = I('post.province2');
				$data['city2'] = I('post.city2');
				$data['county2'] = I('post.county2');
			}
		}elseif (in_array(4,$fieldTemp)){
			$data['province'] = I('post.province');
			$data['city'] = I('post.city');
			$data['county'] = I('post.county');
	    }elseif (in_array(5,$fieldTemp)){
	    	$data['province2'] = I('post.province2');
	    	$data['city2'] = I('post.city2');
	    	$data['county2'] = I('post.county2');
	    }
		if ($this->create($data)){
			$data['name'] = I('post.name');
			$data['tel'] = I('post.tel');
			$data['address'] = I('post.address');
			$data['post'] = I('post.post');
			$data['note'] = I('post.note');
			$data['email'] = I('post.email');
			if (I('post.type')=='a' || (in_array(4,$fieldTemp) && !in_array(5,$fieldTemp))){
				$data['province'] = I('post.province');
				$data['city'] = I('post.city');
				$data['county'] = I('post.county');
			}elseif (I('post.type')=='b' || (in_array(5,$fieldTemp) && !in_array(4,$fieldTemp))){
				$data['province'] = I('post.province2');
				$data['city'] = I('post.city2');
				$data['county'] = I('post.county2');
			}
			if ($type && $object['verify']){
				$Verify = new Verify();
				if (!$Verify->check(I('post.verify'),I('post.tid'))) return '验证码不正确！'; 
			}
			if ($type && $this->repeat($object['qq'])) return $object['often'];
			if ($type && C('ORDER_URL')=='0') return $data;
			$id = $this->add($data);
			if ($id){
				return $type ? $data : $id;
			}else{
				return 0;
			}
		}else{
			return $this->getError();
		}
	}
	
	//修改
	public function update(){
		$data = array(
			'tid'=>I('post.tid'),
			'pid'=>I('post.pid'),
			'price'=>I('post.price'),
			'count'=>I('post.count'),
			'pay'=>I('post.pay'),
			'state'=>I('post.state'),
			'lid'=>I('post.lid'),
			'logistics_id'=>I('post.logistics_id')
		);
		$Template = D('Admin/Template');
		$object = $Template->one(I('post.tid'));
		$fieldTemp = explode(',',$object['field']);
		if (in_array(2,$fieldTemp)) $data['name'] = I('post.name');
		if (in_array(3,$fieldTemp)) $data['tel'] = I('post.tel');
		if (in_array(4,$fieldTemp) || in_array(5,$fieldTemp)){
			$data['province2'] = I('post.province2');
			$data['city2'] = I('post.city2');
			$data['county2'] = I('post.county2');
		}
		if (in_array(6,$fieldTemp)) $data['address'] = I('post.address');
		if (in_array(7,$fieldTemp)) $data['post'] = I('post.post');
		if (in_array(8,$fieldTemp)) $data['note'] = I('post.note');
		if (in_array(9,$fieldTemp)) $data['email'] = I('post.email');
		$map['id'] = I('get.id');
		$map['recycle'] = $this->recycle;
		$map[] = $this->where;
		if ($this->create($data)){
			$data['name'] = I('post.name');
			$data['tel'] = I('post.tel');
			$data['province'] = I('post.province2');
			$data['city'] = I('post.city2');
			$data['county'] = I('post.county2');
			$data['address'] = I('post.address');
			$data['post'] = I('post.post');
			$data['note'] = I('post.note');
			$data['email'] = I('post.email');
			$id = $this->where($map)->save($data);
			return $id ? $id : 0;
		}else{
			return $this->getError();
		}
	}
	
	//修改支付状态
	public function update2($oid,$pay){
		$map['oid'] = $oid;
		$data['pay'] = $pay; 
		$id = $this->where($map)->save($data);
		return $id ? $id : 0;
	}
	
	//验证重复
	private function repeat($qq){
		$map = array(
			'_complex'=>array(
				'ip'=>$_SERVER['REMOTE_ADDR'],
				'_logic'=>'OR'
			),
			'recycle'=>0,
			'date'=>array('EGT',time()-C('ORDER_TIME')*60)
		);
		if ($qq){
			$session = session('QC_userData');
			$map['_complex']['qqau'] = $session['openid'];
		}
		return $this->field('id')->where($map)->find();
	}
	
	//回收
	public function recycle(){
		$map['id'] = I('get.id') ? I('get.id') : array('IN',I('post.ids'));
		$map[] = $this->where;
		$data['recycle'] = 1; 
		$id = $this->where($map)->save($data);
		return $id ? $id : 0;
	}
	
	//还原
	public function recover(){
		$map['id'] = I('get.id') ? I('get.id') : array('IN',I('post.ids'));
		$map[] = $this->where;
		$data['recycle'] = 0; 
		$id = $this->where($map)->save($data);
		return $id ? $id : 0;
	}
	
	//删除
	public function remove(){
		$map['id'] = I('get.id') ? I('get.id') : array('IN',I('post.ids'));
		$map[] = $this->where;
		$affected_rows = $this->where($map)->delete();
		if ($affected_rows) $this->execute('OPTIMIZE TABLE `__PREFIX__order`');
		return $affected_rows;
	}
	
	//批量修改订单状态
	public function state(){
		$map['id'] = array('IN',I('post.ids'));
		$map[] = $this->where;
		$data['state'] = I('post.state'); 
		$id = $this->where($map)->save($data);
		return $id ? $id : 0;
	}
	
	//批量修改物流
	public function multi(){
		foreach (explode("\r\n",I('post.multi')) as $value){
			$value = explode('|',$value);
			if (count($value) != 3) return '批量修改格式有误！';
			$map['oid'] = $value[0];
			$map[] = $this->where;
			$data = array(
				'lid'=>$value[1],
				'logistics_id'=>$value[2]
			);
			$this->where($map)->save($data);
		}
		return 1;
	}
	
	//高级搜索
	private function map($recycle=0){
		if (in_array(I('get.field'),array(0,1))) $map['_complex']['oid'] = array('like','%'.I('get.keyword').'%');
		if (in_array(I('get.field'),array(0,2))) $map['_complex']['name'] = array('like','%'.I('get.keyword').'%');
		if (in_array(I('get.field'),array(0,3))) $map['_complex']['tel'] = array('like','%'.I('get.keyword').'%');
		if (in_array(I('get.field'),array(0,4))) $map['_complex']['province'] = array('like','%'.I('get.keyword').'%');
		if (in_array(I('get.field'),array(0,5))) $map['_complex']['city'] = array('like','%'.I('get.keyword').'%');
		if (in_array(I('get.field'),array(0,6))) $map['_complex']['county'] = array('like','%'.I('get.keyword').'%');
		if (in_array(I('get.field'),array(0,7))) $map['_complex']['address'] = array('like','%'.I('get.keyword').'%');
		if (in_array(I('get.field'),array(0,8))) $map['_complex']['post'] = array('like','%'.I('get.keyword').'%');
		if (in_array(I('get.field'),array(0,9))) $map['_complex']['email'] = array('like','%'.I('get.keyword').'%');
		if (in_array(I('get.field'),array(0,10))) $map['_complex']['ip'] = array('like','%'.I('get.keyword').'%');
		if (in_array(I('get.field'),array(0,11))) $map['_complex']['referrer'] = array('like','%'.I('get.keyword').'%');
		if (in_array(I('get.field'),array(0,12))) $map['_complex']['logistics_id'] = array('like','%'.I('get.keyword').'%');
		$map['_complex']['_logic'] = 'OR';
		if (I('get.uid',-1) != -1) $map['uid'] = I('get.uid');
		if (I('get.tid')) $map['tid'] = I('get.tid');
		if (I('get.pid')) $map['pid'] = I('get.pid');
		if (I('get.pay')) $map['pay'] = I('get.pay');
		if (I('get.state')) $map['state'] = I('get.state');
		if (I('get.lid')) $map['lid'] = I('get.lid');
		$map['_string'] = '1=1';
		if (I('get.price1')) $map['_string'] .= " AND `price`>='".I('get.price1')."'";
		if (I('get.price2')) $map['_string'] .= " AND `price`<='".I('get.price2')."'";
		if (I('get.count1')) $map['_string'] .= " AND `count`>='".I('get.count1')."'";
		if (I('get.count2')) $map['_string'] .= " AND `count`<='".I('get.count2')."'";
		if (I('get.total1')) $map['_string'] .= " AND `price`*`count`>='".I('get.total1')."'";
		if (I('get.total2')) $map['_string'] .= " AND `price`*`count`<='".I('get.total2')."'";
		if (I('get.date1')) $map['_string'] .= " AND `date`>='".strtotime(I('get.date1').' 00:00:00')."'";
		if (I('get.date2')) $map['_string'] .= " AND `date`<='".strtotime(I('get.date2').' 23:59:59')."'";
		$map['recycle'] = $recycle;
		$map[] = $this->where;
		return $map;
	}
}